package data;

import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

public class GetSeries {
    private String start;
    private String end;
    private String operator;
    private String tableName;
    private String span;
    private static final Logger logger = Logger.getLogger(GetSeries.class);

    public GetSeries(String start, String end, String operator, String tableName, String span) {
        this.start = start;
        this.end = end;
        this.operator = operator;
        this.tableName = tableName;
        this.span = span;
    }

    public JSONObject getSeriesData(Connection connection) {
        String sql;
        String format = this.getFormat();
        if (this.operator.equals("")) {
            sql = "select DATE_FORMAT(execute_time,'" + format + "') days,count(id) count from " + tableName
                    + " where execute_time < ? and execute_time > ? group by days";
        } else {
            sql = "select DATE_FORMAT(execute_time,'" + format + "') days,count(id) count from " + tableName
                    + " where execute_time < ? and execute_time > ? and operator = ? group by days";
        }
        JSONObject jsonObject = new JSONObject();
        HashMap<String, Integer> hashMap = new HashMap<>();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, this.end);
            preparedStatement.setString(2, this.start);
            if (!this.operator.equals("")) {
                preparedStatement.setString(3, this.operator);
            }
            ResultSet result = preparedStatement.executeQuery();
            while (result != null && result.next()) {
                hashMap.put(result.getString("days"), result.getInt("count"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (this.span.equals("day")) {//天为跨度
            Calendar startCalendar = this.getFirstDayCalendar(this.start);
            if (startCalendar != null) {
                startCalendar.add(Calendar.DATE, 1);
                Calendar endCalendar = this.getFirstDayCalendar(this.end);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (endCalendar != null) {
                    for (; startCalendar.compareTo(endCalendar) < 0; startCalendar.add(
                            Calendar.DATE, 1)) {
                        String str = sdf.format(startCalendar.getTime());
                        jsonObject.put(str, hashMap.getOrDefault(str, 0));
                    }
                } else {
                    logger.error("日期转化calendar对象失败");
                }
            } else {
                logger.error("日期转化calendar对象失败");
            }
        } else {//小时为跨度
            for (int i = 0; i < 24; i++) {
                jsonObject.put(i, hashMap.getOrDefault(String.valueOf(i), 0));
            }
        }
        return jsonObject;
    }

    private String getFormat() {
        Properties properties = new Properties();
        InputStreamReader inputStreamReader = null;
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("dateFormat.properties");
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            properties.load(inputStreamReader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String format = properties.getProperty(this.span);
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return format;
    }

    private Calendar getFirstDayCalendar(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(str);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
